// pages/storer/bouter.js
var app = getApp();
var api = require('../../utils/api.js');
var rsa = require('../../utils/rsa.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsArr: [],
    inputValue: '', //输入框内容
    totalNum: 0,
    delBtnWidth: 180
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },


  edit: function (e) {

    //编辑收货地址 省略

  },



  add: function () {

    //增加收货地址 省略

  },



  delItem: function (e) {

    var id = e.currentTarget.dataset.id;

    var index = e.currentTarget.dataset.index;

    this.data.address.splice(index, 1);

    this.setData({

      address: this.data.address

    })

  },



  touchS: function (e) {

    if (e.touches.length == 1) {

      this.setData({

        //设置触摸起始点水平方向位置

        startX: e.touches[0].clientX

      });

    }

  },



  touchM: function (e) {

    if (e.touches.length == 1) {

      //手指移动时水平方向位置

      var moveX = e.touches[0].clientX;

      //手指起始点位置与移动期间的差值

      var disX = this.data.startX - moveX;

      var delBtnWidth = this.data.delBtnWidth;

      var txtStyle = "";

      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变

        txtStyle = "left:0rpx";

      } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离

        txtStyle = "left:-" + disX + "rpx";

        if (disX >= delBtnWidth) {

          //控制手指移动距离最大值为删除按钮的宽度

          txtStyle = "left:-" + delBtnWidth + "rpx";

        }

      }

      //获取手指触摸的是哪一项

      var index = e.currentTarget.dataset.index;

      var list = this.data.goodsArr;

      list[index]['txtStyle'] = txtStyle;

      //更新列表的状态

      this.setData({

        goodsArr: list

      });

    }

  },

  touchE: function (e) {

    if (e.changedTouches.length == 1) {

      //手指移动结束后水平位置

      var endX = e.changedTouches[0].clientX;

      //触摸开始与结束，手指移动的距离

      var disX = this.data.startX - endX;

      var delBtnWidth = this.data.delBtnWidth;

      //如果距离小于删除按钮的1/2，不显示删除按钮

      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0rpx";

      //获取手指触摸的是哪一项

      var index = e.currentTarget.dataset.index;

      var list = this.data.goodsArr;

      var del_index = '';

      disX > delBtnWidth / 2 ? del_index = index : del_index = '';

      list[index].txtStyle = txtStyle;

      //更新列表的状态

      this.setData({

        goodsArr: list,

        del_index: del_index

      });

    }

  },







  //减少-1
  minusAction: function(e) {
    const index = e.currentTarget.dataset.info;
    var arr = this.data.goodsArr;
    var tempdic = arr[index];
    var valu = parseInt(tempdic.amount) - 1;
    if (valu == 0) return;
    tempdic.amount = valu;
    arr.splice(index, 1, tempdic);
    this.setData({
      goodsArr: arr,
    })
  },
  //修改数据 
  bindManual: function(e) {
    const index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var goar = this.data.goodsArr;
    var tempdic = goar[index];
    tempdic.reValue = value;
    goar.splice(index, 1, tempdic);
    this.setData({
      goodsArr: goar,
    })
  },

  //加+1
  plusAction: function(e) {
    const index = e.currentTarget.dataset.info;
    var arr = this.data.goodsArr;
    var tempdic = arr[index];
    var valu = parseInt(tempdic.amount) + 1;
    if (valu == 0) return;
    tempdic.amount = valu;
    arr.splice(index, 1, tempdic);
    this.setData({
      goodsArr: arr,
    })
  },
  //删除某一列
  deleCellAction: function(e) {
    var tempArr = this.data.goodsArr;
    const vale = e.currentTarget.dataset.info;
    console.log(vale);
    tempArr.splice(vale, 1);
    this.setData({
      goodsArr: tempArr,
      totalNum: tempArr.length,
    })
  },
  //输入框输入
  bindRcodeInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  //扫描
  scanAction: function() {
    wx.scanCode({
      success: (res) => {
        console.log(res.result);
        this.requestGoodsDetail(res.result);
      }
    })
  },
  //搜索
  searchAction: function() {
    const vale = this.data.inputValue;
    if (vale !== '') {
      this.requestGoodsDetail(vale);
    }

  },
  //查询商品
  requestGoodsDetail: function(e) {
    // wx.showToast({
    //   title: '成功',
    //   icon: 'success',
    //   duration: 2000
    // })
    // return;
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'goods.keyword',"seller_bn": shopnum,'session_id': settion,"keyword": e}, (err, res) => {
      var redata = res.data.list;
      if (redata.length == 0) {
        wx.showToast({
          title: '未查询到商品',
          icon: 'none',
          duration: 2000
        })
        return;
      }
        var good_detail = redata[0];
        var gooArr = this.data.goodsArr;
        var cprice = parseFloat(good_detail.price).toFixed(2);
        var bnum = good_detail.bn
        var tempArr = {
          name: good_detail.name,
          gnum: good_detail.barcode,
          price: cprice,
          amount: good_detail.quantity,
          samount: good_detail.quantity,
          id: bnum,
          txtStyle:'',
          reValue:0,
        };
        gooArr.splice(0, 0, tempArr);
        var total = gooArr.length;
        this.setData({
          goodsArr: gooArr,
          totalNum: total,
        })
      
      
      

    });
  },
  //重置价格
  resetPrice: function(e) {
    console.log("price:" + e);
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    var goar = this.data.goodsArr;
    var tempdic = goar[index];
    tempdic.price = value;
    goar.splice(index, 1, tempdic);
    this.setData({
      goodsArr: goar,
    })
  },
  getCurrentTime: function() {
    var date = new Date();
    var year = date.getFullYear();
    var m = date.getMonth() + 1;
    var month = m < 10 ? '0' + m : m;
    var day = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
  },
  //盘点
  markSureAction: function() {
    var gd = this.data.goodsArr;
    if (gd.length == 0) return;
    var ctime = this.getCurrentTime();
    var handle_user = app.globalData.shopName;
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    var outArr = [];
    // { name: good_detail.product_name, gnum: e, price: cprice, amount: good_detail.store_count, samount: good_detail.store_count };
    for (var i = 0; i < gd.length; i++) {
      var temp = gd[i];
      var pcode = temp.id;
      var num = temp.amount;
      var cost = temp.reValue;
      var dic = {
        "good_bn": pcode,
        "stock": cost,
        "remark": num
      };
      outArr.push(dic);
    }
    var that = this;
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'goods.store_check',
      'session_id': settion,
      "seller_bn": shopnum,
      "remark": '',
      'goods_data': outArr
    }, (err, res) => {
      if (!res || res == '') {
        wx.showToast({
          title: err,
          icon: 'success',
          duration: 2000
        })
        return;
      }
      if (res.return_code == '0000') {
        wx.showModal({
          title: '提示',
          content: res.return_msg,
          success: function(res) {
            that.setData({
              goodsArr: [],
              totalNum: 0,
            })
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        wx.showToast({
          title: res.return_msg,
          icon: 'success',
          duration: 2000
        })
      }
    });
  }
})